<script setup lang="ts">
import { ref, reactive, onBeforeUnmount } from 'vue';
import { hideLoading, showLoading, usePullDownRefresh, stopPullDownRefresh, showToast } from '@tarojs/taro';
import { useNurseOrders } from '@/service';
import { useAuthStore } from '@/store';
import { storeToRefs } from 'pinia';
import { useDayjs, useEmitter } from '@/hooks/common';
import { useImage } from '@/hooks';
import { useRouterPush } from '@/composables';
import { SUCCESS_MSG_DURATION } from '@/constants';

const emitter = useEmitter();

emitter.$on('order_refresh', () => getData());

onBeforeUnmount(() => {
    emitter.$off('order_refresh');
});

const { toGoodsPay, toComment, toRefund, toBill } = useRouterPush();

const { nurseUser } = storeToRefs(useAuthStore());

const { $dayjs } = useDayjs();

definePageConfig({
    navigationBarTitleText: '服务',
    enablePullDownRefresh: true
});

const { list, closeByWeChat } = useNurseOrders();

const nurseType = ref([
    { text: '全部', value: 0 },
    { text: '住院陪护', value: 1 },
    { text: '居家陪护', value: 2 },
    { text: '就诊陪护', value: 3 },
    { text: '母婴护理', value: 4 },
    { text: '单项服务', value: 5 },
    { text: '共享租赁椅', value: 6 }
]);

const status = ref([
    { text: '全部', value: 0 },
    { text: '待支付', value: 1 },
    { text: '已支付', value: 2 },
    { text: '已取消', value: 3 },
    { text: '已评价', value: 4 },
    { text: '退款中', value: 8 },
    { text: '退款异常', value: 6 },
    { text: '退款成功', value: 7 }
]);

usePullDownRefresh(() => {
    getData();
    stopPullDownRefresh();
});
const data: any = ref([]);

const param = reactive<any>({
    beginDate: $dayjs().add(-45, 'day').format('YYYY-MM-DD'),
    endDate: $dayjs().format('YYYY-MM-DD'),
    nurseType: 0,
    date: '',
    status: 0
});
getData();

async function getData() {
    if (!nurseUser.value?.id) return;

    data.value.length = 0;

    showLoading({ title: '正在请求数据...' });

    const { error, success } = await list(`?nurseType=${param.nurseType}&userId=${nurseUser.value.id}
   &beginDate=${param.beginDate} 00:00:00&endDate=${param.endDate} 23:59:59&status=${param.status}`);

    if (!error && success) data.value = success;

    hideLoading();
}
const dateShow = ref(false);

const confirm = () => {
    param.beginDate = $dayjs(param.date[0]).format('YYYY-MM-DD');
    param.endDate = $dayjs(param.date[1]).format('YYYY-MM-DD');
    getData();
    dateShow.value = false;
};
const nurseTypeChange = (value: number) => {
    param.nurseType = value;
    getData();
};

const statusChange = (value: number) => {
    param.status = value;
    getData();
};

async function toPay(item: any, pay?: string) {
    toGoodsPay({
        pname: item.orderText,
        pic: useImage(item.pic),
        orderId: item.id,
        status: item.status,
        pay
    });
}
const rowRecrod = ref();

const visible_delete = ref(false);

const loading = ref(false);

async function close() {
    loading.value = true;
    showLoading({ title: '正在取消...' });
    const { error, success } = await closeByWeChat(rowRecrod.value.id);
    if (!error && success) {
        hideLoading();
        showToast({
            title: '取消成功',
            icon: 'success',
            duration: SUCCESS_MSG_DURATION
        });
    }
    loading.value = false;
    getData();
}
function cancelOrder(item: any) {
    rowRecrod.value = item;
    visible_delete.value = true;
}
</script>
<template>
    <basic-layout show-tab-bar>
        <!-- <custom-navbar title="服务" /> -->
        <view class="w-375px text-primary flex justify-between items-center bg-#fff text-14px">
            <nut-menu class="w-120px">
                <nut-menu-item v-model="param.nurseType" :options="nurseType" @change="nurseTypeChange" />
            </nut-menu>
            <view class="flex-col-center w-160px h-48px">
                <view class="w-full flex items-center mt-1" @click="dateShow = true">
                    <view>开始日期:</view>
                    <view class="ml-4 b-b-solid b-b-1">
                        {{ param.beginDate }}
                    </view>
                </view>
                <view class="w-full flex items-center mt-1" @click="dateShow = true">
                    <view>结束日期:</view>
                    <view class="ml-4 b-b-solid b-b-1">
                        {{ param.endDate }}
                    </view>
                </view>
            </view>
            <view class="w-95px flex flex-row flex-center">
                <nut-menu class="w-110px">
                    <nut-menu-item v-model="param.status" :options="status" @change="statusChange" />
                </nut-menu>
            </view>
        </view>

        <view class="w-375px flex-col-center">
            <view v-for="item in data" class="w-350px flex-col-center">
                <view class="w-full h-220px b-rounded-3 px-1 shadow items-center bg-#fff flex-col my-2">
                    <view class="w-full flex h-40px justify-between items-center">
                        <view class="w-5/6 flex items-center h-24px text-primary">
                            <nut-ellipsis direction="end" class="h-24px" :content="item.orderText"></nut-ellipsis>
                            <view class="i-local-right-bold w-20px h-20px" />
                        </view>
                        <view class="w-1/6 flex items-center">
                            <nut-tag v-if="item.status == '1'" type="primary">待支付</nut-tag>
                            <nut-tag v-if="item.status == '2'" type="success">已完成</nut-tag>
                            <nut-tag v-if="item.status == '3'" type="warning">已取消</nut-tag>
                            <nut-tag v-if="item.status == '4'" color="#059669">已评价</nut-tag>
                            <nut-tag v-if="item.status == '8'" type="primary">退款中</nut-tag>
                            <nut-tag v-if="item.status == '6'" type="danger">退款异常</nut-tag>
                            <nut-tag v-if="item.status == '7'" type="primary">退款成功</nut-tag>
                        </view>
                    </view>
                    <view class="w-full flex h-120px justify-between items-center" @click.stop="toPay(item, '0')">
                        <view class="w-120px h-120px">
                            <image :src="useImage(item.pic)" alt="" class="_img" draggable="false" />
                        </view>
                        <view class="w-220px text-14px flex-col justify-start items-start">
                            <view>{{ `订单时间:${item.createTime}` }}</view>
                            <view class="mt-1">{{ `监护人:${item.family_name}` }}</view>
                            <view class="mt-1">{{ `数量:${item.num}` }}</view>
                            <view class="mt-1">{{ `单价:${item.price}` }}</view>
                            <view class="mt-1">{{ `总金额:${item.amt}` }}</view>
                        </view>
                    </view>
                    <view class="flex-center w-full h-60px">
                        <view class="flex justify-around w-full">
                            <nut-button v-if="item.status == '2'" class="font-bold" plain size="small" type="info"
                                @click="toComment(item.id)">
                                追加评价
                            </nut-button>
                            <nut-button v-if="item.status == '1'" class="font-bold" plain size="small" type="warning"
                                @click.stop="cancelOrder(item)">
                                取消订单
                            </nut-button>
                            <nut-button v-if="item.status == '1'" class="font-bold mr-4" plain size="small"
                                type="primary" @click.stop="toPay(item, '1')">
                                立即支付
                            </nut-button>
                            <nut-button v-if="item.status == '2' && item.invoiceStatus !== '1'" class="font-bold mr-4"
                                plain size="small" type="primary" @click.stop="toBill(item.id, item.amt)">
                                申请开票
                            </nut-button>
                            <nut-button v-if="item.status == '2' || item.status == '4'" class="font-bold mr-4" plain
                                size="small" type="warning" @click.stop="toRefund(item.id)">
                                申请退款
                            </nut-button>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <nut-empty v-if="data?.length == 0" description="暂无订单"></nut-empty>
        <nut-popup v-model:visible="dateShow" position="bottom">
            <view class="mb-15">
                <nut-calendar-card v-model="param.date" type="range"></nut-calendar-card>
                <basic-button text="确认" class="mt-2" @on-click="confirm" />
            </view>
        </nut-popup>
        <nut-dialog v-model:visible="visible_delete" title="提示" content="是否取消该订单？" @cancel="visible_delete = false"
            @ok="close" />
    </basic-layout>
</template>
<style lang="scss">
.nut-menu-item__content {
    padding: var(--nut-menu-item-content-padding, 24rpx 48rpx);
    max-height: 428px;
    display: flex;
    flex-wrap: wrap;
}

.nut-theme-dark {
    .nut-menu {
        .nut-menu__bar {
            background-color: $dark-background;

            .nut-menu__item {
                color: $dark-color;
            }
        }
    }
}

.nut-menu {
    &.scroll-fixed {
        position: fixed;
        top: $menu-scroll-fixed-top;
        z-index: $menu-scroll-fixed-z-index;
        width: 100%;
    }

    .nut-menu__bar {
        position: relative;
        display: flex;
        line-height: $menu-bar-line-height;
        background-color: $white;
        box-shadow: none;

        &.opened {
            z-index: $menu-bar-opened-z-index;
        }

        .nut-menu__item {
            flex: 1;
            text-align: center;
            font-size: $menu-item-font-size;
            color: var(--nut-menu-item-content-padding, 24rpx 48rpx);
            min-width: 0;

            &.active {
                color: $menu-item-active-text-color;
            }

            &.disabled {
                color: $menu-item-disabled-color;
            }

            .nut-menu__title-icon {
                transition: all 0.2s linear;
                display: flex;
            }

            .nut-menu__title {
                display: flex;
                align-items: center;
                justify-content: center;
                max-width: 100%;

                .nut-menu__title-text {
                    @include text-ellipsis;
                    display: block;
                    padding-left: $menu-title-text-padding-left;
                    padding-right: $menu-title-text-padding-right;
                }

                &.active .nut-menu__title-icon {
                    transform: rotate(180deg);
                }
            }
        }
    }
}

._img {
    height: 100%;
    width: 100%;
    border-radius: 24rpx;
    // border-bottom-left-radius: 24rpx;
}
</style>
